import React, { useState } from "react";
import { Form, Input, Button, message } from "antd";
import api from "@/fetch";

import "./index.less";

const RegistrationForm: React.FC<{
  handleSetIsLogin: (isLogin: boolean) => void;
}> = (props) => {
  const [isLoading, setIsLoading] = useState(false);

  const onFinish = (values: {
    phone: string;
    realName: string;
    password: string;
  }) => {
    setIsLoading(true);
    api
      .post("/api/v1/auth/register", values)
      .then(() => {
        message.success("注册成功，快去登录吧！");
      })
      .catch((error) => {
        message.error(error?.message || "注册失败");
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  return (
    <Form
      name="registration_form"
      onFinish={onFinish}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
    >
      <Form.Item
        label="手机号码"
        name="phone"
        rules={[
          { required: true, message: "请输入手机号码!" },
          {
            pattern: /^[1-9]\d{10}$/,
            message: "请输入正确的手机号码!",
          },
        ]}
      >
        <Input className="custom-input" />
      </Form.Item>

      <Form.Item
        label="真实姓名"
        name="realName"
        rules={[{ required: true, message: "请输入您的真实姓名!" }]}
      >
        <Input className="custom-input" />
      </Form.Item>

      <Form.Item
        label="密码"
        name="password"
        rules={[
          { required: true, message: "请输入密码!" },
          { min: 5, message: "密码不能少于5个字符!" },
          { max: 16, message: "密码不能大于16个字符!" },
        ]}
      >
        <Input.Password className="custom-input" />
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 6, span: 18 }}>
        <div className="btn-center">
          <Button type="primary" htmlType="submit" loading={isLoading}>
            注册
          </Button>
        </div>
        <div
          onClick={() => props.handleSetIsLogin(true)}
          className="btn-center"
          style={{ marginTop: "20px", cursor: "pointer", color: "blue" }}
        >
          登录
        </div>
      </Form.Item>
    </Form>
  );
};

export default RegistrationForm;
